package com.jack.xiaoer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jack.xiaoer.constant.ShopStateEnum;
import com.jack.xiaoer.constant.ShopTypeEnum;
import com.jack.xiaoer.dao.ShopMapper;
import com.jack.xiaoer.dto.ShopDTO;
import com.jack.xiaoer.entity.Category;
import com.jack.xiaoer.entity.Shop;
import com.jack.xiaoer.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/11.
 */
@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Override
    public IPage<Shop> listShop(Integer pageNum, Integer pageSize) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", ShopStateEnum.ON_SALE);
        Page<Shop> page = new Page<>(pageNum, pageSize);

        IPage<Shop> shopPage = shopMapper.selectPage(page, queryWrapper);
        return shopPage;
    }

    @Override
    public Shop createShop(Optional<Shop> shop) {
        if (!shop.isPresent()) return null;

        final Shop shopStored = shop.get();
        shopStored.setType(ShopTypeEnum.COMMON);
        shopStored.setState(ShopStateEnum.ON_SALE);
        shopStored.setGmtCreate(Instant.now());
        shopStored.setGmtModified(Instant.now());

        int row = shopMapper.insert(shopStored);
        if (row > 0) {
            return shopStored;
        }

        return null;
    }

    @Override
    public ShopDTO getShopDetail(Long shopId) {
        if (shopId == null || shopId < 0)
            return null;

        ShopDTO shopDTO = new ShopDTO();

        Shop shop = shopMapper.selectById(shopId);
        List<Category> categoryList = shopMapper.getCategoryListByShopId(shopId);

        if (shop == null)
            return null;

        shopDTO.setCategoryList(categoryList);
        BeanUtils.copyProperties(shop, shopDTO);

        return shopDTO;
    }

}
